package com.ruicar.afs.cloud.account.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.account.common.dto.VoucherTemplateEventsDto;
import com.ruicar.afs.cloud.account.common.entity.VoucherInfo;
import com.ruicar.afs.cloud.account.common.entity.VoucherTemplateEvents;
import com.ruicar.afs.cloud.account.common.mapper.VoucherTemplateEventsMapper;
import com.ruicar.afs.cloud.account.common.service.VoucherInfoService;
import com.ruicar.afs.cloud.account.common.service.VoucherTemplateEventsService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.uid.UidGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.VoucherStatus;
import com.ruicar.afs.cloud.common.voucher.handle.VoucherCaches;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author infinity
 * @version 1.0
 * @date 2020/7/4 18:37
 */
@Service
public class VoucherTemplateEventsServiceImpl extends ServiceImpl<VoucherTemplateEventsMapper, VoucherTemplateEvents> implements VoucherTemplateEventsService {
    @Autowired
    private VoucherInfoService voucherInfoService;
    @Autowired
    private UidGenerator uidGenerator;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addVoucherEvents(VoucherTemplateEventsDto dto) {
        check(dto);
        VoucherTemplateEvents voucherTemplateEvents = VoucherTemplateEvents.convertFromDto(dto);
        this.save(voucherTemplateEvents);
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delVoucherEvents(Long id) {
        this.update(Wrappers.<VoucherTemplateEvents>lambdaUpdate().eq(VoucherTemplateEvents::getId, id)
                .set(VoucherTemplateEvents::getDeleteToken, uidGenerator.getUID())
                //逻辑删除 1 为删除
                .set(VoucherTemplateEvents::getDelFlag, '1'));
        return Boolean.TRUE;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyVoucherEvents(VoucherTemplateEventsDto dto) {
        check(dto);
        VoucherTemplateEvents voucherTemplateEvents = this.getById(dto.getId());
        BeanUtil.copyProperties(dto, voucherTemplateEvents,  "createBy", "createTime", "id", "deleteToken");
        this.updateById(voucherTemplateEvents);
        return Boolean.TRUE;
    }

    @Override
    public Boolean active(Long id) {
        VoucherTemplateEvents events = this.getById(id);
        Assert.isTrue(events != null, "数据不存在!");
        if (VoucherStatus.ACTIVE.equals(events.getStatus())) {
            return Boolean.TRUE;
        }
        VoucherTemplateEventsDto dto =new VoucherTemplateEventsDto();
        dto.setMainBusinessCode(events.getMainBusinessCode());
        dto.setChildBusinessCode(events.getChildBusinessCode());
        dto.setId(events.getId());
        dto.setBuriedPointNo(events.getBuriedPointNo());
        check(dto);
        events.setStatus(VoucherStatus.ACTIVE);
        this.updateById(events);
        VoucherCaches.resetCache();
        return Boolean.TRUE;
    }

    @Override
    public Boolean invalidity(Long id) {
        VoucherTemplateEvents events = this.getById(id);
        Assert.isTrue(events != null, "数据不存在!");
        if (VoucherStatus.INVALIDITY.equals(events.getStatus())) {
            return Boolean.TRUE;
        }
        events.setStatus(VoucherStatus.INVALIDITY);
        this.updateById(events);
        VoucherCaches.resetCache();
        return Boolean.TRUE;
    }

    @Override
    public IResponse queryVoucherEventsList(QueryCondition<VoucherTemplateEventsDto> condition) {
        VoucherTemplateEventsDto dto= condition.getCondition();
        dto.setEventStatus(dto.getStatus()!=null?AfsEnumUtil.key(dto.getStatus()):null);
        dto.setMainBusinessCode(StringUtils.isNotBlank(dto.getMainBusinessCode())?dto.getMainBusinessCode().trim():dto.getMainBusinessCode());
        dto.setChildBusinessCode(StringUtils.isNotBlank(dto.getChildBusinessCode())?dto.getChildBusinessCode().trim():dto.getChildBusinessCode());
        dto.setBuriedPointNo(StringUtils.isNotBlank(dto.getBuriedPointNo())?dto.getBuriedPointNo().trim():dto.getBuriedPointNo());
        return IResponse.success(this.baseMapper.queryVoucherEventsList(new Page(condition.getPageNumber(), condition.getPageSize()),dto));
    }

    private void check(VoucherTemplateEventsDto dto) {
        long count = voucherInfoService.count(Wrappers.<VoucherInfo>lambdaQuery()
                .eq(VoucherInfo::getMainBusinessCode, dto.getMainBusinessCode())
                .eq(VoucherInfo::getChildBusinessCode, dto.getChildBusinessCode())
                .eq(VoucherInfo::getStatus, AfsEnumUtil.key(VoucherStatus.ACTIVE)));
        Assert.isTrue(count > 0, "生效凭证模板中，主事件代码：[" + dto.getMainBusinessCode() + "],子事件代码：[" + dto.getChildBusinessCode() + "]不存在！");
        count = this.baseMapper.selectCount(Wrappers.<VoucherTemplateEvents>lambdaQuery().eq(VoucherTemplateEvents::getBuriedPointNo, dto.getBuriedPointNo())
                .eq(VoucherTemplateEvents::getMainBusinessCode, dto.getMainBusinessCode()).eq(VoucherTemplateEvents::getChildBusinessCode, dto.getChildBusinessCode()).ne(dto.getId() != null, VoucherTemplateEvents::getId, dto.getId()));
        Assert.isTrue(count < 1, "相同凭证埋点事件，主事件代码：[" + dto.getMainBusinessCode() + "],子事件代码：[" + dto.getChildBusinessCode() + "]重复！");
    }
}
